from typing import Optional, Callable

from .check_conditions import check_conditions
from .executor import AbstractExecutor, ExecutionContext, Tuple,Schema
class FilterExecutor(AbstractExecutor):
    """过滤执行器
    
    根据谓词条件过滤元组
    """
    
    def __init__(self, context: ExecutionContext, child: AbstractExecutor,plan):
        super().__init__(context,child.get_output_schema())
        self.child = child
        # 这里的谓词条件是一个返回bool的lambda函数
        self.conditions = plan

    def init(self) -> None:
        """初始化过滤器"""
        self.child.init()
    
    def next(self) -> Optional[Tuple]:
        """获取下一个满足条件的元组"""
        while True:
            input_tuple = self.child.next()
            if input_tuple is None:
                return None
            
            # 将 Tuple 转换为 {列名: 值}，以匹配测试中的谓词(record_dict)接口
            # record_values = input_tuple.get_values()
            # names = [name for name, _ in (self.schema.fields if self.schema else [])]
            # record_dict = {names[i]: record_values[i] for i in range(min(len(names), len(record_values)))}
            # 检查是否满足谓词条件
            if check_conditions(input_tuple, self.conditions):
                return input_tuple